Introduction to React Native Styling – Detailed Notes
Course: React Native Training
Topic: Introduction to React Native Styling
Course Link: React Native Training Course
Demo Link: Register for a Free Course Demo
JustAcademy Website: Visit JustAcademy
1. Introduction to React Native Styling
React Native styling is the process of controlling the appearance and layout of application components. It allows developers to customize text, backgrounds, spacing, borders, dimensions, alignment, and other visual properties of mobile applications.
React Native provides a styling system inspired by CSS, but it uses JavaScript objects rather than traditional CSS files. Styles are commonly defined using JavaScript objects or the StyleSheet.create() method.
Styling helps developers create attractive, consistent, responsive, and user-friendly interfaces for Android and iOS applications.
Example
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
export default function App() {
return (
<View style={styles.container}>
<Text style={styles.title}>Welcome to React Native</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F2F5F9',
},
title: {
fontSize: 24,
fontWeight: 'bold',
color: '#222222',
},
});
In this example, the container fills the available space and centers the text horizontally and vertically. The title has a larger font size, bold text, and a custom color.
2. Learning Objectives
After completing this topic, learners should be able to:
- Understand how styling works in React Native.
- Differentiate React Native styling from traditional CSS.
- Use inline styles and reusable style objects.
- Create styles with
StyleSheet.create().
- Apply colors, fonts, spacing, dimensions, borders, and shadows.
- Arrange components using Flexbox.
- Understand style precedence and inheritance limitations.
- Build reusable and maintainable styling structures.
- Recognize common styling mistakes and troubleshoot them.
3. How Styling Works in React Native
In React Native, the style prop accepts a JavaScript object or an array of style objects. These styles are interpreted by React Native and applied to native UI elements on the platform.
Unlike a typical web application, React Native does not use a browser DOM or automatically load regular CSS stylesheets.
Example
import React from 'react';
import { View, Text } from 'react-native';
export default function App() {
return (
<View style={{ backgroundColor: 'lightblue', padding: 20 }}>
<Text style={{ fontSize: 20, color: 'navy' }}>
Styled React Native Text
</Text>
</View>
);
}
The outer View has a light-blue background and padding, while the Text component uses a larger font and navy text color.
4. React Native Styling vs Traditional CSS
| Feature |
React Native |
Traditional CSS |
| Style definition |
JavaScript objects |
CSS rules and declarations |
| Property naming |
Usually camelCase, such as backgroundColor |
Usually kebab-case, such as background-color |
| Style units |
Many dimensions use unitless numbers representing logical layout units |
Commonly uses px, rem, %, and other units |
| Layout |
Flexbox is commonly used |
Flexbox, Grid, block layout, and other systems |
| Selectors |
No regular CSS selectors |
Element, class, ID, attribute, and other selectors |
| Style files |
Styles are usually defined in JavaScript or TypeScript files |
Styles are commonly stored in CSS files |
| Platform rendering |
Styles are applied to native interface components |
Styles are applied by the browser rendering engine |
5. The Style Prop
The style prop is used to customize the appearance of a React Native component. Components such as View, Text, and Image support styles, although the properties supported by each component differ.
Example
<View style={{ padding: 16, backgroundColor: '#E8F0FE' }}>
<Text style={{ fontSize: 18, color: '#173B75' }}>
Learn React Native
</Text>
</View>
Important Points
- The value of
style is commonly a JavaScript object.
- Style property names use camelCase.
- String values are used for properties such as colors and some enumerated settings.
- Numeric dimensions usually represent logical units rather than CSS pixels.
- Each component supports a specific set of style properties.
6. Inline Styling
Inline styling means writing style properties directly inside a component's style prop. It is useful for small examples, quick prototypes, and styles that depend on a simple expression.
Example
import React from 'react';
import { View, Text } from 'react-native';
export default function App() {
return (
<View style={{ padding: 20, backgroundColor: '#FFF3E0' }}>
<Text style={{ fontSize: 22, color: '#C45100' }}>
Inline Styling Example
</Text>
</View>
);
}
Advantages
- Easy to write and understand in small components.
- Useful for quick experiments.
- Can use JavaScript expressions to calculate style values.
Disadvantages
- Large components can become difficult to read.
- Repeated styles may be duplicated across multiple components.
- Separating layout and presentation becomes harder as the application grows.
Best practice: Use inline styles for simple or dynamic cases, and move reusable styles into named objects or a stylesheet when the component becomes more complex.
7. Using Style Objects
A style object is a JavaScript object containing visual properties. It can be defined separately and then assigned to the style prop.
Example
const cardStyle = {
backgroundColor: '#FFFFFF',
padding: 16,
borderRadius: 12,
borderWidth: 1,
borderColor: '#D9DEE7',
};
const titleStyle = {
fontSize: 20,
fontWeight: 'bold',
color: '#202124',
};
// Usage:
// <View style={cardStyle}>
// <Text style={titleStyle}>Product Card</Text>
// </View>
Named style objects improve readability and make it easier to reuse a visual pattern. For larger projects, StyleSheet.create() is a common way to organize these styles.
8. Using StyleSheet.create()
StyleSheet is provided by React Native and can be used to organize styles into a single object. The StyleSheet.create() method helps structure named styles and can provide useful development-time checks and editor support.
Syntax
import { StyleSheet } from 'react-native';
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
},
heading: {
fontSize: 24,
fontWeight: 'bold',
},
});
Complete Example
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
export default function App() {
return (
<View style={styles.container}>
<Text style={styles.heading}>React Native Styling</Text>
<Text style={styles.description}>
Organize your styles for better readability.
</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 24,
justifyContent: 'center',
backgroundColor: '#F7F8FA',
},
heading: {
fontSize: 26,
fontWeight: 'bold',
color: '#1D3557',
marginBottom: 12,
},
description: {
fontSize: 16,
color: '#555555',
lineHeight: 24,
},
});
Benefits of StyleSheet.create()
- Keeps styles organized and separate from component markup.
- Makes styles easier to reuse and update.
- Provides clear names for visual properties.
- Can improve development-time validation and maintainability.
- Helps keep larger components easier to read.
9. Understanding Colors
Colors affect the appearance, readability, and identity of an application. React Native supports named colors and common color formats such as hexadecimal, RGB, and RGBA strings for supported color properties.
Example
const styles = StyleSheet.create({
screen: {
backgroundColor: '#F5F7FA',
},
primaryText: {
color: '#1D4ED8',
},
successText: {
color: 'green',
},
translucentPanel: {
backgroundColor: 'rgba(0, 0, 0, 0.1)',
},
});
Common Color Properties
| Property |
Purpose |
Example |
color |
Sets text color |
color: '#222222' |
backgroundColor |
Sets the component background |
backgroundColor: '#F3F4F6' |
borderColor |
Sets the border color |
borderColor: '#CCCCCC' |
tintColor |
Applies tinting to supported image content |
tintColor: '#2563EB' |
Best practice: Choose colors that provide sufficient contrast between text and its background. Do not use color alone to communicate important status information.
10. Font Styling and Text Appearance
Text styling controls how information appears on the screen. Common properties include font size, font weight, font family, line height, letter spacing, and text alignment.
Example
const styles = StyleSheet.create({
heading: {
fontSize: 28,
fontWeight: 'bold',
color: '#111827',
textAlign: 'center',
marginBottom: 12,
},
paragraph: {
fontSize: 16,
lineHeight: 24,
color: '#4B5563',
textAlign: 'left',
},
label: {
fontSize: 14,
letterSpacing: 0.5,
fontWeight: '600',
},
});
Important Text Properties
| Property |
Description |
fontSize |
Controls the size of text. |
fontWeight |
Controls text thickness using supported weight values. |
fontFamily |
Specifies a font family available to the platform or bundled application. |
fontStyle |
Can apply values such as normal or italic where supported. |
lineHeight |
Controls the height of each line of text. |
letterSpacing |
Controls spacing between characters. |
textAlign |
Aligns text, for example left, center, or right. |
textTransform |
Controls text capitalization using supported values. |
Some text-related properties are specific to the Text component. They should not be assumed to work on every component.
11. Dimensions, Width, and Height
Dimensions determine the size of components. React Native supports properties such as width, height, minWidth, maxWidth, minHeight, and maxHeight on applicable components.
Example
const styles = StyleSheet.create({
fixedBox: {
width: 200,
height: 100,
backgroundColor: '#BFDBFE',
},
flexibleBox: {
width: '100%',
minHeight: 120,
padding: 16,
backgroundColor: '#DCFCE7',
},
});
Numeric width and height values generally use logical layout units. Percentage dimensions are relative to the relevant parent layout and require the parent to provide a suitable size.
Fixed vs Flexible Dimensions
- Fixed dimensions: Useful for elements that need a predictable size, such as icons or small controls.
- Flexible dimensions: Useful for content that should adapt to available space.
- Minimum and maximum dimensions: Useful for preventing components from becoming too small or too large.
Prefer flexible layouts where possible so that the application works on devices with different screen sizes and font settings.
12. Margin and Padding
Margin and padding control spacing, but they serve different purposes.
- Margin: Creates space outside a component's border.
- Padding: Creates space inside a component, between its content and its border.
Example
const styles = StyleSheet.create({
card: {
margin: 16,
padding: 20,
backgroundColor: '#FFFFFF',
borderRadius: 10,
},
title: {
marginBottom: 8,
},
});
Common Spacing Properties
| Property |
Purpose |
margin |
Sets spacing outside all sides. |
marginTop |
Sets top outer spacing. |
marginBottom |
Sets bottom outer spacing. |
marginHorizontal |
Sets left and right outer spacing. |
marginVertical |
Sets top and bottom outer spacing. |
padding |
Sets inner spacing on all sides. |
paddingHorizontal |
Sets left and right inner spacing. |
paddingVertical |
Sets top and bottom inner spacing. |
13. Borders and Rounded Corners
Borders can separate elements, outline cards, and make buttons visually distinct. Rounded corners can soften the appearance of cards, images, and controls.
Example
const styles = StyleSheet.create({
card: {
borderWidth: 1,
borderColor: '#D1D5DB',
borderRadius: 12,
padding: 16,
backgroundColor: '#FFFFFF',
},
primaryButton: {
borderRadius: 8,
borderWidth: 0,
paddingVertical: 12,
paddingHorizontal: 20,
backgroundColor: '#2563EB',
},
});
Common Border Properties
borderWidth: controls border thickness.
borderColor: controls border color.
borderRadius: rounds the corners.
borderTopWidth and borderBottomWidth: control individual border edges.
borderStyle: controls supported border styles.
Border behavior can vary with platform and component details. Test the appearance on both Android and iOS when consistent rendering is important.
14. Flexbox Fundamentals
Flexbox is the primary layout system used in many React Native interfaces. It allows developers to arrange components in rows or columns, distribute available space, and align elements.
React Native uses Flexbox concepts similar to those found on the web, but its default settings differ. In particular, flexDirection defaults to column in React Native.
Example
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
},
box: {
width: 100,
height: 100,
margin: 8,
backgroundColor: '#93C5FD',
},
});
Important Flexbox Properties
| Property |
Purpose |
Common Values |
flex |
Controls how a component grows or uses available space. |
1, 2 |
flexDirection |
Sets the main layout direction. |
row, column |
justifyContent |
Distributes children along the main axis. |
center, space-between, flex-start |
alignItems |
Aligns children along the cross axis. |
center, stretch, flex-start |
alignSelf |
Overrides cross-axis alignment for one child. |
center, flex-end |
flexWrap |
Allows items to wrap when space is limited. |
wrap, nowrap |
gap |
Sets spacing between children where supported by the project's React Native version. |
Numeric values |
15. Understanding flex: 1
The flex: 1 property is commonly used to make a component occupy the available space in its parent layout. Its final effect depends on the surrounding layout and sibling components.
Example
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
export default function App() {
return (
<View style={styles.container}>
<View style={styles.header}>
<Text>Header</Text>
</View>
<View style={styles.content}>
<Text>Main Content</Text>
</View>
<View style={styles.footer}>
<Text>Footer</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
header: {
height: 70,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#DBEAFE',
},
content: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F3F4F6',
},
footer: {
height: 60,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#D1FAE5',
},
});
The header and footer use fixed heights, while the content area expands to occupy the remaining available space.
16. Combining Multiple Styles
React Native allows multiple styles to be combined using an array. Later styles in the array override earlier styles when they define the same property.
Example
const styles = StyleSheet.create({
box: {
padding: 16,
backgroundColor: '#E5E7EB',
},
highlighted: {
backgroundColor: '#FDE68A',
borderWidth: 2,
borderColor: '#D97706',
},
});
// Usage:
// <View style={[styles.box, styles.highlighted]} />
In this example, the final background color is the one specified in styles.highlighted. The padding from styles.box remains because the second style does not override it.
Conditional Styling
Conditional styling is useful when a component's appearance depends on application state or a property.
const styles = StyleSheet.create({
button: {
padding: 12,
borderRadius: 8,
},
active: {
backgroundColor: '#2563EB',
},
inactive: {
backgroundColor: '#9CA3AF',
},
});
// Example:
// <View style={[styles.button, isActive ? styles.active : styles.inactive]} />
Make sure the condition is defined in the component before using it. This pattern is useful for active buttons, selected items, validation states, and status indicators.
17. Styling Components with Reusable Patterns
Reusable styles help maintain a consistent design throughout an application. For example, an application can use shared styles for headings, cards, buttons, labels, and form fields.
Example
const styles = StyleSheet.create({
screen: {
flex: 1,
padding: 20,
backgroundColor: '#F9FAFB',
},
card: {
padding: 16,
marginBottom: 16,
borderRadius: 12,
backgroundColor: '#FFFFFF',
borderWidth: 1,
borderColor: '#E5E7EB',
},
heading: {
fontSize: 20,
fontWeight: 'bold',
color: '#111827',
marginBottom: 8,
},
body: {
fontSize: 15,
lineHeight: 22,
color: '#4B5563',
},
});
When multiple screens need the same design, shared style constants or a common theme module can reduce duplication and simplify future changes.
18. Styling Buttons
Buttons should be visually clear and easy to tap. Their styles often include background color, padding, rounded corners, and text contrast. React Native provides several button and touchable components, and the styling options depend on which component is used.
Example Using Pressable
import React from 'react';
import { View, Text, Pressable, StyleSheet } from 'react-native';
export default function App() {
return (
<View style={styles.container}>
<Pressable
style={styles.button}
onPress={() => console.log('Button pressed')}
>
<Text style={styles.buttonText}>Get Started</Text>
</Pressable>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
button: {
backgroundColor: '#2563EB',
paddingVertical: 14,
paddingHorizontal: 24,
borderRadius: 10,
},
buttonText: {
color: '#FFFFFF',
fontSize: 16,
fontWeight: 'bold',
},
});
For production applications, also consider pressed, disabled, loading, and accessibility states. A button should have an adequate touch target and a clear label.
19. Styling Images and Image Containers
Images often need dimensions, rounded corners, or a layout container. React Native's Image component supports styles for its size and positioning, while resizeMode controls how image content fits into the available area.
Example
import React from 'react';
import { View, Image, StyleSheet } from 'react-native';
export default function App() {
return (
<View style={styles.container}>
<Image
source={{ uri: 'https://example.com/photo.jpg' }}
style={styles.image}
resizeMode="cover"
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
padding: 20,
},
image: {
width: 240,
height: 160,
borderRadius: 12,
backgroundColor: '#E5E7EB',
},
});
The example URL is a placeholder and must be replaced with a valid image URL. In an actual project, handle loading, network failures, and image dimensions appropriately.
20. Shadows and Elevation
Shadows can create a sense of depth and help cards or floating elements stand out. The supported styling approach differs between platforms.
Example
const styles = StyleSheet.create({
card: {
padding: 20,
borderRadius: 12,
backgroundColor: '#FFFFFF',
elevation: 4,
shadowColor: '#000000',
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.15,
shadowRadius: 4,
},
});
elevation is commonly used for Android shadow depth.
shadowColor, shadowOffset, shadowOpacity, and shadowRadius control shadow appearance on supported platforms.
- Shadow rendering can differ between Android and iOS.
Test shadows on real devices or emulators. Use them sparingly to maintain a clean visual hierarchy.
21. Positioning Elements
React Native supports relative and absolute positioning. Relative positioning keeps a component in the normal layout flow, while absolute positioning places it relative to its containing layout.
Example
const styles = StyleSheet.create({
container: {
width: 220,
height: 140,
backgroundColor: '#DBEAFE',
position: 'relative',
},
badge: {
position: 'absolute',
top: 8,
right: 8,
padding: 6,
backgroundColor: '#F97316',
borderRadius: 6,
},
});
This example places a badge near the top-right corner of the container. Absolute positioning is useful for badges, overlays, and icons, but excessive use can cause layout problems on smaller screens.
22. Responsive Styling and Different Screen Sizes
Responsive styling allows interfaces to adapt to different device dimensions, orientations, and content sizes. React Native layouts can often adapt naturally when developers use Flexbox, flexible widths, and sensible spacing.
Recommended Techniques
- Use
flex: 1 where components should fill available space.
- Prefer flexible layouts over unnecessary fixed widths.
- Use
minWidth and maxWidth where supported and appropriate.
- Test portrait and landscape orientations when the app supports both.
- Account for longer text and larger accessibility font settings.
- Use
useWindowDimensions() when styles genuinely need to respond to changing window dimensions.
Example Using useWindowDimensions
import React from 'react';
import { View, Text, StyleSheet, useWindowDimensions } from 'react-native';
export default function App() {
const { width } = useWindowDimensions();
const compact = width < 400;
return (
<View style={styles.container}>
<Text style={[styles.title, compact && styles.compactTitle]}>
Responsive Heading
</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
},
title: {
fontSize: 28,
fontWeight: 'bold',
},
compactTitle: {
fontSize: 22,
},
});
useWindowDimensions() updates when the window dimensions change, making it suitable for layouts that react to orientation or window-size changes. The example uses a simple width threshold; real applications should choose breakpoints based on their design needs.
23. Platform-Specific Styling
Sometimes the same design needs small adjustments on Android and iOS. React Native provides the Platform API to detect the current platform and choose appropriate values.
Example
import { Platform, StyleSheet } from 'react-native';
const styles = StyleSheet.create({
card: {
padding: 16,
backgroundColor: '#FFFFFF',
...Platform.select({
ios: {
shadowColor: '#000000',
shadowOpacity: 0.12,
shadowRadius: 5,
shadowOffset: { width: 0, height: 2 },
},
android: {
elevation: 4,
},
default: {},
}),
},
});
Use platform-specific styling only when needed. A consistent design should remain understandable and usable across both platforms, even when small visual differences are necessary.
24. Understanding Style Inheritance
React Native does not follow the same broad CSS inheritance model as a web browser. Text-related styles can flow between nested Text components, but styles applied to a parent View do not automatically apply to every nested component.
Example
<View style={{ color: 'blue' }}>
<Text>This text does not inherit color from the View.</Text>
</View>
<Text style={{ color: 'blue', fontSize: 18 }}>
Blue parent text
<Text style={{ fontWeight: 'bold' }}>
{' '}with a bold nested section
</Text>
</Text>
In the first example, the text color should be set on the Text component itself. In the second example, the nested Text can use text styling from its parent while applying an additional bold weight.
25. Style Precedence and Conditional Values
When styles are combined, later styles in a style array take precedence for properties they share. This makes it possible to define a base style and then apply variations.
Example
const styles = StyleSheet.create({
base: {
padding: 12,
backgroundColor: '#E5E7EB',
},
selected: {
backgroundColor: '#BFDBFE',
},
warning: {
borderWidth: 1,
borderColor: '#DC2626',
},
});
// Selected style overrides the base background:
// <View style={[styles.base, isSelected && styles.selected]} />
// Warning style adds a border:
// <View style={[styles.base, hasError && styles.warning]} />
Boolean conditions can be used in a style array when a style should be applied only if a condition is true. Ensure that the condition is a boolean or another valid expression that evaluates to a style object or a falsy value.
26. Styling with a Theme
A theme is a shared collection of design values, such as colors, spacing, and typography. Themes help maintain consistency and make it easier to implement light and dark modes.
Example
export const theme = {
colors: {
primary: '#2563EB',
background: '#F9FAFB',
surface: '#FFFFFF',
text: '#111827',
muted: '#6B7280',
border: '#E5E7EB',
},
spacing: {
small: 8,
medium: 16,
large: 24,
},
typography: {
heading: 24,
body: 16,
caption: 12,
},
};
A component can use these values rather than repeating literal numbers and colors throughout the project.
import { StyleSheet } from 'react-native';
import { theme } from './theme';
const styles = StyleSheet.create({
container: {
flex: 1,
padding: theme.spacing.large,
backgroundColor: theme.colors.background,
},
title: {
fontSize: theme.typography.heading,
color: theme.colors.text,
},
});
For larger applications, theme values can be combined with React Context or another state-management approach to share the selected theme across screens.
27. Common Styling Mistakes
| Mistake |
Why It Happens |
Solution |
| Using CSS property names |
Web CSS syntax is used by mistake. |
Use camelCase, such as backgroundColor. |
| Adding units to numeric dimensions |
CSS syntax is copied directly. |
Use numbers for common dimensions, such as width: 200. |
| Using unsupported properties |
Not every CSS property exists in React Native. |
Check the component's supported style properties. |
| Expecting View styles to inherit |
Web inheritance rules are assumed. |
Apply text properties directly to Text. |
| Using too many fixed dimensions |
Layouts are designed for only one screen. |
Prefer flexible layouts and test multiple screen sizes. |
| Combining styles in the wrong order |
Later styles overwrite earlier values. |
Review the style array from left to right. |
| Ignoring text accessibility |
Only default font sizes are tested. |
Test larger text sizes and avoid clipping. |
| Using inconsistent colors and spacing |
Values are repeated throughout the app. |
Use shared style objects or theme values. |
28. Debugging Styling Problems
When a component does not look as expected, investigate its style properties and its parent layout. A style may be correct but have no visible effect because the component has no available space, another style overrides it, or the property is unsupported.
Debugging Checklist
- Confirm that the component supports the style property.
- Check spelling and camelCase formatting.
- Inspect the parent container's dimensions and Flexbox properties.
- Check whether another style later in an array overrides the property.
- Temporarily apply a visible background color to understand component boundaries.
- Use React Native DevTools or the available inspector to examine component layout.
- Test on the target platform and device sizes.
- Check whether long text, font scaling, or content size causes unexpected layout changes.
Example: Fixing an Uncentered Component
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
box: {
width: 180,
height: 100,
backgroundColor: '#BFDBFE',
},
});
For a child component to be centered within the available screen area, the parent typically needs a suitable size and the correct alignment properties.
29. Styling Best Practices
- Use
StyleSheet.create() to organize reusable static styles.
- Choose descriptive names such as
container, heading, and primaryButton.
- Keep styles close to their component or in a shared style module when appropriate.
- Reuse colors, spacing, and typography through theme values.
- Use Flexbox to build layouts that adapt to available space.
- Limit unnecessary inline objects in complex components.
- Use conditional style arrays for clear, state-dependent variations.
- Maintain adequate contrast and readable typography.
- Test on Android and iOS when both platforms are supported.
- Consider safe areas, keyboard visibility, screen orientation, and larger text sizes.
- Avoid absolute positioning for entire layouts unless the design requires it.
- Keep visual styles consistent across screens and reusable components.
30. Practical Project: Create a Styled Profile Card
In this project, you will create a simple profile card using React Native styling. The card includes a title, descriptive text, a colored container, spacing, rounded corners, and a button.
Project Code
import React from 'react';
import { View, Text, Pressable, StyleSheet, Alert } from 'react-native';
export default function App() {
return (
<View style={styles.screen}>
<View style={styles.card}>
<Text style={styles.title}>Developer Profile</Text>
<Text style={styles.name}>Alex Johnson</Text>
<Text style={styles.description}>
React Native learner focused on building mobile applications.
</Text>
<Pressable
style={styles.button}
onPress={() => Alert.alert('Profile', 'Profile button pressed')}
>
<Text style={styles.buttonText}>View Profile</Text>
</Pressable>
</View>
</View>
);
}
const styles = StyleSheet.create({
screen: {
flex: 1,
justifyContent: 'center',
padding: 20,
backgroundColor: '#F3F4F6',
},
card: {
padding: 24,
backgroundColor: '#FFFFFF',
borderRadius: 16,
borderWidth: 1,
borderColor: '#E5E7EB',
},
title: {
fontSize: 14,
fontWeight: '600',
color: '#6B7280',
marginBottom: 12,
},
name: {
fontSize: 24,
fontWeight: 'bold',
color: '#111827',
marginBottom: 8,
},
description: {
fontSize: 16,
lineHeight: 24,
color: '#4B5563',
marginBottom: 20,
},
button: {
alignSelf: 'flex-start',
paddingVertical: 12,
paddingHorizontal: 18,
backgroundColor: '#2563EB',
borderRadius: 8,
},
buttonText: {
fontSize: 16,
fontWeight: 'bold',
color: '#FFFFFF',
},
});
Project Explanation
- Screen container: Uses
flex: 1 and padding to create a screen layout.
- Card: Uses a white background, border, padding, and rounded corners.
- Title: Uses a smaller font and muted color to establish hierarchy.
- Name: Uses a larger, bold font to emphasize the main information.
- Description: Uses line height and a readable font size for comfortable reading.
- Button: Uses padding, a blue background, and rounded corners to look interactive.
- Button action: Displays an alert when the button is pressed.
31. Practice Exercises
Exercise 1: Basic Styling
- Create a screen with a background color.
- Add a heading and a subtitle.
- Change their font sizes, colors, and alignment.
Exercise 2: Card Design
- Create a card using
View.
- Add padding, margin, a border, and rounded corners.
- Place a title and description inside the card.
Exercise 3: Flexbox Layout
- Create three boxes inside a parent container.
- Arrange them in a row using
flexDirection: 'row'.
- Experiment with
justifyContent and alignItems.
Exercise 4: Conditional Styling
- Create a component with an active and inactive state.
- Use a style array to change the background color based on the state.
- Confirm that the correct style takes precedence.
Exercise 5: Responsive Layout
- Create a profile card with flexible width.
- Test it on different screen sizes.
- Check that the content remains readable without clipping.
32. Interview Questions and Answers
Q1. What is styling in React Native?
Answer: Styling is the process of defining the appearance and layout of React Native components using JavaScript style objects and supported style properties.
Q2. How is React Native styling different from CSS?
Answer: React Native styles are written as JavaScript objects, generally use camelCase property names, and are applied to native UI components rather than browser DOM elements.
Q3. What is the purpose of StyleSheet.create()?
Answer: It organizes named styles in a reusable object and can provide useful development-time validation and tooling support.
Q4. What is inline styling?
Answer: Inline styling means passing a style object directly to a component's style prop.
Q5. What is the difference between margin and padding?
Answer: Margin creates space outside a component's border, while padding creates space between its content and border.
Q6. What is Flexbox?
Answer: Flexbox is a layout system that arranges components and controls alignment and distribution of space along main and cross axes.
Q7. What does flex: 1 do?
Answer: It allows a component to use available space according to the surrounding Flexbox layout and its sibling components.
Q8. How can multiple styles be combined?
Answer: Multiple styles can be passed in an array, such as style={[styles.base, styles.active]}. Later styles override earlier styles for matching properties.
Q9. Does React Native support CSS files directly?
Answer: Standard React Native styling uses JavaScript objects rather than regular CSS files. Some frameworks and libraries provide additional styling approaches, but their behavior depends on the tool being used.
Q10. How can styles change according to a condition?
Answer: Use a conditional expression to choose between styles or include a style conditionally in a style array.
Q11. How do you make a layout responsive?
Answer: Use Flexbox, flexible dimensions, appropriate constraints, and, when necessary, useWindowDimensions() to adapt to available screen dimensions.
Q12. What is the purpose of a theme?
Answer: A theme centralizes design values such as colors, spacing, and typography so that an application remains consistent and easier to maintain.
Q13. Can styles be inherited from a parent View?
Answer: Most styles are not inherited from a parent View in the same way as web CSS. Text styles can flow through nested Text components.
Q14. How can platform-specific styles be applied?
Answer: Use the React Native Platform API, such as Platform.select(), when a visual adjustment is needed for a particular platform.
Q15. How do you debug an unexpected layout?
Answer: Inspect the component and its parent, check supported properties and dimensions, review style-array order, and use React Native DevTools or the available inspector.
33. Quick Revision Checklist
- Understand the React Native style prop.
- Know when to use inline styles and
StyleSheet.create().
- Remember camelCase style property names.
- Know common colors, font, spacing, border, and dimension properties.
- Understand Flexbox direction and alignment.
- Use
flex: 1 appropriately within a parent layout.
- Combine styles using arrays and conditional expressions.
- Build reusable styles and shared theme values.
- Consider responsive layouts and platform-specific differences.
- Test accessibility, text scaling, and multiple device sizes.
34. Conclusion
React Native styling is an essential skill for building polished and usable mobile applications. It allows developers to control the appearance of components, establish consistent design patterns, and create flexible layouts using JavaScript objects and Flexbox.
Start by learning the style prop, inline styles, and StyleSheet.create(). Then practice typography, colors, dimensions, spacing, borders, and Flexbox. As applications grow, use reusable styles, themes, conditional styling, and responsive layout techniques to keep the code maintainable.
For structured learning, explore the React Native Training Course at JustAcademy or register for a course demo.
35. Additional Learning Resources